<template>
  <div style="div">
    <el-upload
      ref="upload"
      action="#"
      list-type="picture-card"
      :limit="fileNum"
      :on-exceed="exceeds"
      :on-change="changeUpload"
      :on-remove="handleRemove"
      :file-list="fileList"
      :class="{hide:hideUpload}"
      :auto-upload="false"
      :disabled="disabled"
    >
      <i slot="default" class="el-icon-plus" />
      <div slot="file" slot-scope="{file}">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt>
      </div>
    </el-upload>
  </div>
</template>
<script>
import { policy } from '@/api/policy'
import $ from 'jquery'
export default {
  props: {
    disabled: Boolean,
    fileList: Array,
    fileNum: Number,
    imgUploadFlag: Boolean,
    imgUploadFlag100: Boolean
    //   hideUpload:Boolean,
    //   required: true
  },
  data() {
    return {
      changes: true,
      hideUpload: false,
      imgUrl: '',
      imgFlag: [],
      aliyunOssToken: [],
      listObj: {}
      // imgUploadFlag:true,
    }
  },
  created() {
    this.getPolicy()
  },
  methods: {
    // 获取签名
    getPolicy() {
      policy().then(res => {
        console.log(res)
        this.aliyunOssToken = res.data.data
        this.imgUrl = res.data.data.host
        // var imgUrlPrefix = this.aliyunOssToken.host
        var dir = this.aliyunOssToken.dir
        // localStorage.setItem("imgUrlPrefix",imgUrlPrefix)
        // localStorage.setItem("dir",dir)
      })
    },
    // 图片上传限制提示
    exceeds() {
      this.$message.error('不能上传了')
    },
    // 图片上传改变时
    changeUpload(file, fileList) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const jpg = (testmsg === 'jpg') | 'JPG'
      const png = (testmsg === 'png') | 'PNG'
      const gif = (testmsg === 'gif') | 'GIF'
      if (!jpg && !png && !gif) {
        this.$message({
          message: '上传文件只能是jpg、png、gif格式!',
          type: 'warning'
        })
      }
      if (fileList.length >= this.fileNum) {
        this.changes = true
      } else {
        this.changes = false
      }
      this.hideUpload = fileList.length >= this.fileNum
      // console.log(this.imgUploadFlag);
      var that = this
      // 创建对象
      var img = new Image()
      img.src = file.url
      if (this.imgUploadFlag) {
        // 加载完成执行
        img.onload = function() {
          // console.log(img.width)
          // console.log(img.height)
          // console.log((img.width==1920)&&(img.height==1080))
          if (img.width !== 750 && img.height !== 750) {
            that.hideUpload = false
            that.$refs.upload.clearFiles()
            that.$message.error('请选择宽度、高度都为750的图片')
          }
        }
      }
      if (this.imgUploadFlag100) {
        // 加载完成执行
        img.onload = function() {
          // console.log(img.width)
          // console.log(img.height)
          // console.log((img.width==1920)&&(img.height==1080))
          if (img.width !== 100 && img.height !== 100) {
            that.hideUpload = false
            that.$refs.upload.clearFiles()
            that.$message.error('请选择宽度、高度都为100的图片')
          }
        }
      }
    },
    // 图片移除时
    handleRemove(file, fileList) {
      if (fileList.length >= this.fileNum) {
        this.changes = true
      } else {
        this.changes = false
      }
      this.hideUpload = fileList.length >= this.fileNum
      console.log(fileList)
    },
    changeStatus() {
      return this.changes
    },
    // 字符串截取
    getCaption(obj) {
      var index = obj.lastIndexOf('.com')
      obj = obj.substring(index + 4, obj.length)
      return obj
    },
    // 图片上传
    submitUpload() {
      this.getPolicy()
      this.imgFlag = []
      const _self = this
      const oldList = []
      const newList = []
      // console.log(oldList)
      // console.log(newList)
      for (var i = 0; i < this.$refs.upload.uploadFiles.length; i++) {
        if (this.$refs.upload.uploadFiles[i].name) {
          newList.push(this.$refs.upload.uploadFiles[i])
        } else {
          oldList.push(this.$refs.upload.uploadFiles[i])
        }
      }
      for (var k = 0; k < oldList.length; k++) {
        this.imgFlag.push(this.getCaption(oldList[k].url))
      }
      if (newList.length > 0) {
        for (let k = 0; k < newList.length; ++k) {
          var file = newList[k].name
          var getSuffix = function(fileName) {
            var pos = fileName.lastIndexOf('.')
            var suffix = ''
            if (pos != -1) {
              suffix = fileName.substring(pos)
            }
            return suffix
          }
          // 利用时间戳生成uuid
          var d = new Date().getTime()
          if (
            window.performance &&
            typeof window.performance.now === 'function'
          ) {
            d += performance.now() // use high-precision timer if available
          }
          var uuid = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'.replace(
            /[xy]/g,
            function(c) {
              var r = (d + Math.random() * 16) % 16 | 0
              d = Math.floor(d / 16)
              return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16)
            }
          )
          // 定义文件名
          var filename = uuid + getSuffix(file)
          // 注意formData里append添加的键的大小写
          var formData = new FormData()
          // 存储在oss的文件路径
          formData.append('OSSAccessKeyId', _self.aliyunOssToken.accessid)
          // accessKeyId
          formData.append('key', _self.aliyunOssToken.dir + '/' + filename)
          // policy
          formData.append('policy', _self.aliyunOssToken.policy)
          // 签名
          // 如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
          formData.append('Signature', _self.aliyunOssToken.signature)
          // 文件详情
          formData.append('file', newList[k].raw)
          // 成功后返回的操作码
          formData.append('success_action_status', 200)
          var url = _self.aliyunOssToken.host
          var fileUrl =
            _self.aliyunOssToken.host +
            '/' +
            _self.aliyunOssToken.dir +
            '/' +
            filename
          this.imgFlag.push('/' + _self.aliyunOssToken.dir + '/' + filename)
          $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function(data) {
              // console.log(data);
            },
            error: function(data) {
              // console.log(data);
              _self.$notify.error({
                title: '错误',
                message: '图片上传失败'
              })
              return 'uploadError'
            }
          })
        }
      }
      return this.imgFlag
    }
  }
}
</script>
<style scoped>
.div,
.div > div {
  display: inline;
}
</style>
